package com.zeros.baselibrary.data.net

import com.zeros.baselibrary.common.BaseConstant
import com.zeros.baselibrary.utils.AppPrefsUtils
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.nio.file.attribute.AclEntry.newBuilder
import java.util.concurrent.TimeUnit

/**
 *   Retrofit工厂，单例  ▏2018/5/16.
 *   wc
 */
class RetrofitFactory private constructor() {

    //1.伴随对象--跟Java中的静态很像
    /*-单例实现-*/
    companion object {
        val instance: RetrofitFactory by lazy { RetrofitFactory() }
    }

    private val retrofit: Retrofit          //需要初始化
    private val interceptor: Interceptor    //需要初始化

    //初始化--
    init {
        //通用拦截
        //lambda:此处chain是参数
        interceptor = Interceptor {
            chain -> val request = chain.request()
                    .newBuilder()
                    .addHeader("Content_Type", "application/json")
                    .addHeader("charset", "UTF-8")
                    .addHeader("token", AppPrefsUtils.getString(BaseConstant.KEY_SP_TOKEN))
                    .build()

            chain.proceed(request)
        }

        //Retrofit实例化
        retrofit = Retrofit.Builder()
                .baseUrl(BaseConstant.SERVER_ADDRESS)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(initClient())   //添加一个OKHttp--Client
                .build()
    }

    //okHttpClient
    private fun initClient(): OkHttpClient {
        return OkHttpClient.Builder()
                .addInterceptor(initLogInterceptor())   //添加自己的拦截器
                .addInterceptor(interceptor)
                .connectTimeout(10, TimeUnit.SECONDS) //连接时间
                .readTimeout(10, TimeUnit.SECONDS)          //超时时间
                .build()
    }

    //构建自己的日志拦截器
    private fun initLogInterceptor(): Interceptor {
        val interceptor = HttpLoggingInterceptor()
        interceptor.level = HttpLoggingInterceptor.Level.BODY
        return interceptor
    }

    /*
    * 具体服务实例化
    */
    fun <T> create(service: Class<T>): T {
        return retrofit.create(service)
    }

}